package com.homeos;

import java.util.Date;
import java.util.Random;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;

public class BroadcastService  extends Service {
	private static final String TAG = "BroadcastService";
	public static final String BROADCAST_ACTION = "com.homeos.displayevent";
	
	private final Handler handler = new Handler();
	Intent intent;
	int counter = 0;
	
	@Override
	public void onCreate() {
		super.onCreate();

		
        PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
        HomeOS.connection.addPacketListener(new PacketListener(){
        public void processPacket(Packet packet) {
        		   Message message = (Message) packet;
        		   bcast(message.getBody());
        		 Log.d("RX:Homeos",""+message.getBody() );
           }
        	   
           }   , filter);
        
        
        
    	intent = new Intent(BROADCAST_ACTION);	
	}
	
    @Override
    public void onStart(Intent intent, int startId) {
        
    	 Bundle bundle = intent.getExtras();
    	 
		 String data = (String) bundle.getCharSequence("subject");
    	Log.d("SERVICE DATA",data);
    	
    	
    	handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 10); // 1 second
   
        
        
    }

    private Runnable sendUpdatesToUI = new Runnable() {
    	public void run() {
    		DisplayLoggingInfo();    		
    	   handler.postDelayed(this,4000); // 4 seconds
    	}
    };    
   
    
    public void bcast(String temp)
    {


    	if(temp.contains("data"))
    	{
    	intent.putExtra("data", temp);
    	//intent.putExtra("counter", String.valueOf(++counter));
    	sendBroadcast(intent);
    	
    	}
    	
    	
    	//handler.postDelayed(sendUpdatesToUI, 7000);
    }
    
    
    private void DisplayLoggingInfo() {
    	
    	Message msg = new Message(HomeOS.homeosID, Message.Type.chat);
    	String fetch = "<get";
    	Random rand = new Random(); 
    	
    	
        msg.setBody(fetch+rand.nextInt(1999999999)+"/>");
        HomeOS.connection.sendPacket(msg);
    	
    	
    }
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {		
        handler.removeCallbacks(sendUpdatesToUI);		
		super.onDestroy();
	}		
}
